﻿using AiChiTu.TraceabilitySystem.Domain.AiChiTuManagement;
using AiChiTu.TraceabilitySystem.ErrorCode;
using AiChiTu.TraceabilitySystem.ErrorCode.Extensions;
using AiChiTu.TraceabilitySystem.Infrastructure.Interfaces;
using AiChiTu.TraceabilitySystem.Read.API.Applications.Commands.Productbasicses;
using AiChiTu.TraceabilitySystem.Read.API.Dtos.Productbasicses;
using CSRedis;
using MediatR;
using Newtonsoft.Json;

namespace AiChiTu.TraceabilitySystem.Read.API.Applications.CommandsHandlers.Productbasicses
{
	/// <summary>
	/// 分页查询商品基础信息请求命令处理
	/// </summary>
	public class QueryPageOfProductbasicCommandHandle : IRequestHandler<QueryPageOfProductbasicCommand, APIResult<APIPaging<QueryPageOfProductbasicDTO>>>
	{
		private readonly IBaseRepository<ProductBasics> productbasicRepository;
		private readonly IBaseRepository<ProductName> productnameRepository;

		public QueryPageOfProductbasicCommandHandle(IBaseRepository<ProductBasics> productbasicRepository, IBaseRepository<ProductName> productnameRepository)
		{
			this.productbasicRepository = productbasicRepository;
			this.productnameRepository = productnameRepository;
		}
		/// <summary>
		/// 分页查询商品基础信息请求命令处理
		/// </summary>
		/// <param name="request">分页查询商品基础信息请求命令</param>
		/// <param name="cancellationToken">取消</param>
		/// <returns>返回任务</returns>
		public async Task<APIResult<APIPaging<QueryPageOfProductbasicDTO>>> Handle(QueryPageOfProductbasicCommand request, CancellationToken cancellationToken)
		{
			APIResult<APIPaging<QueryPageOfProductbasicDTO>> result = new APIResult<APIPaging<QueryPageOfProductbasicDTO>>();
			result.Code = ResultCode.QuerySuccess;
			result.Message = ResultCode.QuerySuccess.GetDescription();

			//// 连接Redis内存数据库
			//CSRedisClient redis = new CSRedisClient("127.0.0.1:6379,defaultDatabase=0");
			//if (!string.IsNullOrEmpty(redis.Get("result.Data")) && redis.Get("Pageindex") == request.Pageindex.ToString() && redis.Get("Pagesize") == request.Pagesize.ToString())
			//{
			//	// 直接读取Redis里缓存的数据
			//	// 先将数据反序列化,再赋值
			//	result.Data = JsonConvert.DeserializeObject<APIPaging<QueryPageOfProductbasicDTO>>(redis.Get("result.Data"));
			//}
			//else
			//{
			//	// 删除Redis里缓存的数据
			//	redis.Del("result.Data");
			//	IQueryable<QueryPageOfProductbasicDTO> query = from a in productbasicRepository.QueryAllAsync(x => !x.IsDeleted)
			//												   join b in productnameRepository.QueryAllAsync() on a.ProductNameId equals b.ProductNameId
			//												   select new QueryPageOfProductbasicDTO
			//												   {
			//													   CreatePerson = a.CreatePerson,
			//													   CreateTime = a.CreateTime,
			//													   UpdatePerson = a.UpdatePerson,
			//													   UpdateTime = a.UpdateTime,
			//													   DeletedPerson = a.DeletedPerson,
			//													   DeletedTime = a.DeletedTime,

			//													   ProductBasicsId = a.ProductBasicsId,
			//													   ProductNameId = a.ProductNameId,
			//													   ProductNameName = b.ProductNamestring,
			//													   Productionbatch = a.Productionbatch,
			//													   Expirationdate = a.Expirationdate,
			//													   ProductionLicenseNumber = a.ProductionLicenseNumber,
			//													   ProductionCompany = a.ProductionCompany,
			//													   ProductPicture = a.ProductPicture,
			//												   };
			//	// productbasicRepository.QueryAllAsync(x => !x.IsDeleted);
			//	int TotalCount = query.Count();
			//	int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.Pagesize);
			//	query = query.Skip((request.Pageindex - 1) * request.Pagesize).Take(request.Pagesize);
			//	APIPaging<QueryPageOfProductbasicDTO> page = new APIPaging<QueryPageOfProductbasicDTO>()
			//	{
			//		TotalCount = TotalCount,
			//		TotalPage = TotalPage,
			//		Data = query.ToList(),
			//	};
			//	result.Data = page;
			//	// 在Redis里记录数据
			//	// 先将数据对象序列化,再记录
			//	redis.Set("Pageindex", request.Pageindex.ToString());
			//	redis.Set("Pagesize", request.Pagesize.ToString());
			//	redis.Set("result.Data", JsonConvert.SerializeObject(result.Data));
			//}
			IQueryable<QueryPageOfProductbasicDTO> query = from a in productbasicRepository.QueryAllAsync(x => !x.IsDeleted)
														   join b in productnameRepository.QueryAllAsync() on a.ProductNameId equals b.ProductNameId
														   select new QueryPageOfProductbasicDTO
														   {
															   CreatePerson = a.CreatePerson,
															   CreateTime = a.CreateTime,
															   UpdatePerson = a.UpdatePerson,
															   UpdateTime = a.UpdateTime,
															   DeletedPerson = a.DeletedPerson,
															   DeletedTime = a.DeletedTime,

															   ProductBasicsId = a.ProductBasicsId,
															   ProductNameId = a.ProductNameId,
															   ProductNameName = b.ProductNamestring,
															   Productionbatch = a.Productionbatch,
															   Expirationdate = a.Expirationdate,
															   ProductionLicenseNumber = a.ProductionLicenseNumber,
															   ProductionCompany = a.ProductionCompany,
															   ProductPicture = a.ProductPicture,
														   };
			// productbasicRepository.QueryAllAsync(x => !x.IsDeleted);
			int TotalCount = query.Count();
			int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.Pagesize);
			query = query.OrderByDescending(x=>x.CreateTime).Skip((request.Pageindex - 1) * request.Pagesize).Take(request.Pagesize);
			APIPaging<QueryPageOfProductbasicDTO> page = new APIPaging<QueryPageOfProductbasicDTO>()
			{
				TotalCount = TotalCount,
				TotalPage = TotalPage,
				Data = query.ToList(),
			};
			result.Data = page;

			return await Task.FromResult(result);
		}
	}
}
